import type { App } from "vue";
import router from "@/router/index";
import * as elIcons from "@element-plus/icons-vue";
import { _download, _get, _post, _put, _delete, http } from "@/utils/axios";
import { useNavTabs } from "@/store/navTabs";
import type { TableColumn } from "@/utils/baTable"; //表格列类型
import Icon from "@/components/icon/index.vue";
import { useBackendMonitor } from "@/store/backend/EquipM/monitor";
import { useWarnLog } from "@/store/backend/EquipM/warn";
import { useDictionary } from "@/store/backend/tool/dictionary";
import { filter, forIn } from "lodash";
import _ from "lodash";
import qs from "qs";
import { useAccess } from "@/store/backend/DeviceM/access";
import { useRegion } from "@/store/backend/SysM/region";
import { useCarbon } from "@/store/backend/EquipM/activeCarbon";
import { useLedgerFile } from "@/store/backend/BusinessM/file";
import { useElectricSubitemByDay } from "@/store/backend/DataM/SubitemByDay";

//实时监控仓库

export function registerIcons(app: App) {
  /*
   * 全局注册 Icon
   * 使用方式: <Icon name="name" size="size" color="color" />
   * 详见<待完善>
   */
  app.component("Icon", Icon);

  /*
   * 全局注册element Plus的icon
   */
  const icons = elIcons as any;
  for (const i in icons) {
    app.component(`el-icon-${icons[i].name}`, icons[i]);
  }
}

async function sendRequest(requestList: any, limits: any, callback: any) {
  // 维护一个promise队列
  const promises = []; // 当前的并发池,用Set结构方便删除
  const pool = new Set(); // set也是Iterable<any>[]类型，因此可以放入到race里
  // 开始并发执行所有的任务
  for (let request of requestList) {
    // 开始执行前，先await 判断 当前的并发任务是否超过限制
    if (pool.size >= limits) {
      // 这里因为没有try catch ，所以要捕获一下错误，不然影响下面微任务的执行
      await Promise.race(pool).catch((err) => err);
    }
    const promise = request(); // 拿到promise
    // 删除请求结束后，从pool里面移除
    const cb = () => {
      pool.delete(promise);
    };
    // 注册下then的任务 第一个cb为resolve状态下的回调 第二个cb为reject
    promise.then(cb, cb);
    pool.add(promise);
    promises.push(promise);
  }
  // 等最后一个for await 结束，这里是属于最后一个 await 后面的 微任务
  // 注意这里其实是在微任务当中了，当前的promises里面是能确保所有的promise都在其中(前提是await那里命中了if)
  Promise.allSettled(promises).then(callback, callback);
}

/**
 * 下拉列表遍历 巡检计化维护人员
 */
export const treePerson = (data: any, name: any, value: any) => {
  let arr: any[] = [];
  data.map((item: any) => {
    let obj: any = {};
    obj.name = item[name];
    obj.value = item[value];
    obj.id = item.id;
    arr.push(obj);
  });
  console.log("下拉列表遍历", arr);
  return arr;
};

/*
 * 默认Url点击事件处理
 */
export const openUrl = (url: string, field: TableColumn) => {
  if (field.target == "_blank") {
    window.open(url);
  } else {
    window.location.href = url;
  }
};

/**
 * 下拉列表遍历
 */
export const tree = (data: any, name: any, value: any) => {
  let arr: any[] = [];
  data.map((item: any) => {
    let obj: any = {};
    obj.name = item[name];
    obj.value = item[value];
    obj.id = item.id;
    arr.push(obj);
  });
  console.log("下拉列表遍历", arr);
  return arr;
};
// 下拉树
export const cascaderTree = (data: any, name: any, value: any) => {
  let arr: any[] = [];
  data.map((item: any) => {
    let obj: any = {};
    obj.label = item[name];
    obj.value = item[value];
    obj.id = item.id;
    arr.push(obj);
  });
  console.log("下拉树", arr);
  return arr;
};

// 本月新增

/*实况历史数据时间选项*/
export const historyTimeFilter = (data: any[]) => {
  console.log("实况", data);

  // { params: { beginTime: stateTime.value[0], endTime: stateTime.value[1] } }
  let obj: any = {};
  for (let i = 0; i < data.length; i++) {
    if (data[i].field === "createTime" || data[i].field === "reportTime") {
      let time = data[i].val.split(",");
      obj = Object.assign(obj, {
        params: { beginTime: time[0], endTime: time[1] },
      });
    } else {
      let key = data[i].field;
      let val = data[i].val;
      obj[key] = val;
    }
  }
  console.log("实况历史数据时间选项", obj);
  return obj;
};

/**
 * 设备接入将从regionId遍历并获取相应名称
 */
export const getRegionName = (data: string) => {
  const Region = useRegion();
  let region = data.split(",");
  let regionNames: any[] = [];
  return new Promise((resolve, reject) => {
    for (let i = 0, len = region.length; i < len; i++) {
      if (region[i] != "1" && region[i] != "2") {
        Region.getName(region[i]).then((res: any) => {
          regionNames.push(res);
          if (regionNames.length == 2) {
            console.log("regionNames", regionNames);
            resolve(regionNames);
          }
        });
      }
    }
  });
};
/**
 * 大屏1分割事件列表重组复制给echarts
 */
export const splitEventList = (data: string) => {
  let arr: string[] = [];
  let head = data.split(" ");
  let end = head[1].split(":");
  arr.push(end[0] + ":" + end[1], head[0]);
  return arr;
};

//修改网关的bank为number
export const changeBankToNumber = (data: any) => {
  let arr: any[] = [];
  data.map((item: any) => {
    item.bank = item.bank - 0;
    arr.push(item);
  });
  console.log("修改网关的bank为number", arr);

  return arr;
};
/**
 * 大屏2设备运行时长key与value分割
 */
export const splitEquipmentsRunTime = (data: any) => {
  // let keyArr = Object.keys(data);
  return new Promise((resolve, reject) => {
    const promises = data.map((item: any) => {
      const getArr = function (list: any) {
        //将value遍历出来
        let arr: any[] = [];
        for (let i = 0, len = list[0].length; i < len; i++) {
          arr.push(list[0][i].value);
        }
        return arr;
      };
      return {
        name: Object.keys(item)[0],
        type: "line",
        stack: "Total",
        data: getArr(Object.values(item)),
      };
    });
    Promise.all(promises).then((res) => {
      resolve(res);
    });
  });
};
//获取key
export const getKey = (data: any) => {
  let keyArr = [];
  for (let i = 0, len = data.length; i < len; i++) {
    keyArr.push(...Object.keys(data[i]));
  }
  return keyArr;
};

/**
 * 大屏2所有设备坐标提取
 */
export const getAddr = (data: any) => {
  let addrArr = [];
  for (let i = 0, len = data.length; i < len; i++) {
    let obj = {
      name: data[i].name,
      id: data[i].id,
      lng: JSON.parse(data[i].coordinate).lng,
      lat: JSON.parse(data[i].coordinate).lat,
      addr: data[i].addr,
      state: data[i].state,
      code: data[i].code,
      productName: data[i].productName,
      remark: data[i].remark,
    };
    addrArr.push(obj);
  }
  return addrArr;
};
/**
 * 大屏2设备告警分类
 */
export const getWarn = (data: any) => {
  let arr = <any>[];
  data.map((item: any) => {
    let itemArr = [item.report_name, item.value];
    arr.push(itemArr);
  });
  return arr;
};

type dictObj = (arr: any[]) => anyObj;
//遍历字典项转为对象
export class DictOperation {
  //处理字典
  getDictData: dictObj = (arr: any[]) => {
    let obj: any = {};
    for (let i = 0, len = arr.length; i < len; i++) {
      obj[arr[i].dictValue] = arr[i].dictLabel;
    }
    return obj;
  };
  //获取字典
  getDictionary = (
    specificClass: any, //pinia仓库类
    dictText: string, //字典名称
    filed: string, //仓库存储的经过处理后的字典对象
    dictStore: string //仓库存储的原始字典数组
  ) => {
    const dictionary = useDictionary();
    if (
      JSON.stringify(specificClass.tags) == "{}" ||
      !(filed == "" ? true : specificClass.tags[filed]) ||
      JSON.stringify(dictionary.moreTags[dictText]) == "{}"
    ) {
      dictionary.getDictInfo(dictText).then((res: any) => {
        let tempTags = this.getDictData(res);
        dictionary.moreTags[dictText] = tempTags;
        specificClass.$patch((state: any) => {
          if (filed != "") {
            state.tags[filed] = tempTags;
          }
          state[dictStore] = res;
        });
      });
    }
  };
  //更新字典moreTags
  updateDictionaryMoreTags = (dictClass: any, val: string) => {
    dictClass.moreTags[val] = {};
  };
}

export const getDictData: dictObj = (arr: any[]) => {
  let obj: any = {};
  for (let i = 0, len = arr.length; i < len; i++) {
    obj[arr[i].dictValue] = arr[i].dictLabel;
  }
  return obj;
};
/**
 * 是否是外部链接
 * @param path
 */
export function isExternal(path: string): boolean {
  return /^(https?|ftp|mailto|tel):/.test(path);
}

/* 加载网络css文件 */
export function loadCss(url: string): void {
  const link = document.createElement("link");
  link.rel = "stylesheet";
  link.href = url;
  link.crossOrigin = "anonymous";
  document.getElementsByTagName("head")[0].appendChild(link);
}

/*设备总量计算*/
export const getSum = (data: any) => {
  let sum = 0;
  for (let i = 0, len = data.length; i < len; i++) {
    sum += data[i].value;
  }
  return sum;
};
// 活性炭总量
export const getSumCarbon = (data: any) => {
  console.log("活性炭总量", data);

  let sum = 0;
  for (let i = 0, len = data.length; i < len; i++) {
    sum += data[i].sum;
  }
  return sum;
};

/* 加载网络js文件 */
export function loadJs(url: string): void {
  const link = document.createElement("script");
  link.src = url;
  document.body.appendChild(link);
}

/**
 * 若依构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(
  data: any,
  id: string,
  parentId: string,
  children: string
) {
  let config = {
    id: id || "id",
    parentId: parentId || "parentId",
    childrenList: children || "children",
  };

  var childrenListMap: anyObj = {};
  var nodeIds: anyObj = {};
  var tree = [];

  for (let d of data) {
    let parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }

  for (let d of data) {
    let parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o: anyObj) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }
  return tree;
}
/*
 * 获取当前月的第一天和最后一天
 */
export const getStart = () => {
  let date = new Date();
  date.setDate(1);
  // let startDay = date.toLocaleDateString().replace(/\//g, "-");
  let startDay =
    date.getFullYear() +
    "-" +
    JSON.stringify(date.getMonth() + 1).padStart(2, "0") +
    "-" +
    JSON.stringify(date.getDate()).padStart(2, "0");
  startDay = startDay + " 00:00:00";
  console.log("前月的第一天", startDay);
  return startDay;
};
export const getEnd = () => {
  let date = new Date();
  date.setMonth(date.getMonth() + 1);
  date.setDate(0);
  // let lastDay = date.toLocaleDateString().replace(/\//g, "-");
  let lastDay =
    date.getFullYear() +
    "-" +
    JSON.stringify(date.getMonth() + 1).padStart(2, "0") +
    "-" +
    JSON.stringify(date.getDate()).padStart(2, "0");
  lastDay = lastDay + " 00:00:00";
  console.log("前月的最后一天", lastDay);
  return lastDay;
};

export class TimeOfPeriod {
  getStart() {
    let date = new Date();
    date.setDate(1);
    // let startDay = date.toLocaleDateString().replace(/\//g, "-");
    let startDay =
      date.getFullYear() +
      "-" +
      JSON.stringify(date.getMonth() + 1).padStart(2, "0") +
      "-" +
      JSON.stringify(date.getDate()).padStart(2, "0");
    startDay = startDay + " 00:00:00";
    console.log("前月的第一天", startDay);
    return startDay;
  }
  getEnd() {
    let date = new Date();
    date.setMonth(date.getMonth() + 1);
    date.setDate(0);
    // let lastDay = date.toLocaleDateString().replace(/\//g, "-");
    let lastDay =
      date.getFullYear() +
      "-" +
      JSON.stringify(date.getMonth() + 1).padStart(2, "0") +
      "-" +
      JSON.stringify(date.getDate()).padStart(2, "0");
    lastDay = lastDay + " 00:00:00";
    console.log("前月的最后一天", lastDay);
    return lastDay;
  }
}

/*
 *将下级权限区域树id遍历出来
 */
export const getLastRegionId = (data: any) => {
  if (data && data.length > 0) {
    let ids: any = [];
    const getArr = function (list: any) {
      for (let i = 0, len = list.length; i < len; i++) {
        if (list[i].children && list[i].children.length > 0) {
          getArr(list[i].children);
        }
        ids.push(list[i].areaId);
      }
    };
    getArr(data);
    return ids;
  } else {
    return [];
  }
};

/*
 * 将权限区域树id遍历出来
 */
export const handleRegionIds = (data: anyObj[]) => {
  let Ids = [];
  for (let i = 0, len = data.length; i < len; i++) {
    Ids.push(data[i].areaId);
  }
  return Ids;
};

/*
 * 打招呼
 */
export const getGreet = () => {
  const now = new Date();
  const hour = now.getHours();
  let greet = "";

  if (hour < 5) {
    greet = "深夜以至，注意休息";
  } else if (hour < 9) {
    greet = "早上好" + "欢迎回来";
  } else if (hour < 12) {
    greet = "早上好" + "欢迎回来";
  } else if (hour < 14) {
    greet = "中午好" + "欢迎回来";
  } else if (hour < 18) {
    greet = "下午好" + "欢迎回来";
  } else if (hour < 24) {
    greet = "晚上好" + "欢迎回来";
  } else {
    greet = "Hello!" + "欢迎回来";
  }
  return greet;
};

/*
 * 将单个设备多条数据遍历出来
 */
export const monitorHistoryOptions = (data: anyObj, type: string) => {
  if (type === "runningTime") {
    let result = [];
    for (let i = 0, len = data.length; i < len; i++) {
      let YMD = data[i].createTime.split(" ")[0];
      result.push([YMD, (Number(data[i][type]) / 3600).toFixed(2)]);
    }
    console.log("resultYMD", result);
    return result;
  } else if (type === "") {
    //默认不选时间时初始化
    let tem = [],
      pa = [],
      flow = [],
      times = [];
    for (let i = 0, len = data.length; i < len; i++) {
      tem.push(Number(data[i].temperature));
      pa.push(Number(data[i].pa));
      flow.push(Number(data[i].flow));
      times.push(data[i].createTime);
    }
    return [pa, flow, tem, times];
  } else {
    let values = [];
    let times = [];
    for (let i = 0, len = data.length; i < len; i++) {
      values.push(Number(data[i][type]));
      times.push(data[i].createTime);
    }
    console.log("[values, times]", [values, times]);

    return [values, times];
  }
};

/**
 * 绘制3d图
 * @param pieData 总数据
 * @param internalDiameterRatio:透明的空心占比
 * @param distance 视角到主体的距离
 * @param alpha 旋转角度
 * @param pieHeight 立体的高度
 * @param opacity 饼或者环的透明度
 */
export const getPie3D = (
  pieData: any,
  internalDiameterRatio: any,
  distance: any,
  alpha: any,
  pieHeight: any,
  opacity = 1
) => {
  const series: any[] = [];
  let sumValue = 0;
  let startValue = 0;
  let endValue = 0;
  let legendData: any[] = [];
  let legendBfb: any[] = [];
  const k = 1 - internalDiameterRatio;
  pieData.sort((a: any, b: any) => {
    return b.value - a.value;
  });
  // 为每一个饼图数据，生成一个 series-surface 配置
  for (let i = 0; i < pieData.length; i++) {
    sumValue += pieData[i].value;
    const seriesItem = {
      name:
        typeof pieData[i].name === "undefined" ? `series${i}` : pieData[i].name,
      type: "surface",
      parametric: true,
      wireframe: {
        show: false,
      },
      pieData: pieData[i],
      pieStatus: {
        selected: false,
        hovered: false,
        k: k,
      },
      center: ["10%", "50%"],
      itemStyle: {},
    };
    if (typeof pieData[i].itemStyle !== "undefined") {
      const itemStyle = {};
      (itemStyle as any).color =
        typeof pieData[i].itemStyle.color !== "undefined"
          ? pieData[i].itemStyle.color
          : opacity;
      (itemStyle as any).opacity =
        typeof pieData[i].itemStyle.opacity !== "undefined"
          ? pieData[i].itemStyle.opacity
          : opacity;
      seriesItem.itemStyle = itemStyle;
    }
    series.push(seriesItem);
  }

  // 使用上一次遍历时，计算出的数据和 sumValue，调用 getParametricEquation 函数，
  // 向每个 series-surface 传入不同的参数方程 series-surface.parametricEquation，也就是实现每一个扇形。
  legendData = [];
  legendBfb = [];
  for (let i = 0; i < series.length; i++) {
    endValue = startValue + series[i].pieData.value;
    series[i].pieData.startRatio = startValue / sumValue;
    series[i].pieData.endRatio = endValue / sumValue;
    series[i].parametricEquation = getParametricEquation(
      series[i].pieData.startRatio,
      series[i].pieData.endRatio,
      false,
      false,
      k,
      series[i].pieData.value
    );
    startValue = endValue;
    const bfb = fomatFloat(series[i].pieData.value / sumValue, 4);
    legendData.push({
      name: series[i].name,
      value: bfb,
    });
    legendBfb.push({
      name: series[i].name,
      value: bfb,
    });
  }
  const boxHeight = getHeight3D(series, pieHeight); // 通过pieHeight设定3d饼/环的高度，单位是px
  // 准备待返回的配置项，把准备好的 legendData、series 传入。
  const option = {
    legend: {
      // show: false,
      data: legendData,
      orient: "horizontal",
      left: 10,
      top: 0,
      itemGap: 15,
      textStyle: {
        color: "#A1E2FF",
      },
      icon: "circle",
      formatter: function (param: any) {
        const item = legendBfb.filter((item: any) => item.name === param)[0];
        const bfs = fomatFloat(item.value * 100, 2) + "%";
        return `${item.name}  ${bfs}`;
      },
    },
    labelLine: {
      show: true,
      lineStyle: {
        color: "#fff",
      },
    },
    label: {
      show: true,
      position: "outside",
      formatter: "{b} \n{c} {d}%",
    },
    tooltip: {
      backgroundColor: "#033b77",
      borderColor: "#21f2c4",
      textStyle: {
        color: "#fff",
        fontSize: 13,
      },
      formatter: (params: any) => {
        if (
          params.seriesName !== "mouseoutSeries" &&
          params.seriesName !== "pie2d"
        ) {
          const bfb = (
            (option.series[params.seriesIndex].pieData.endRatio -
              option.series[params.seriesIndex].pieData.startRatio) *
            100
          ).toFixed(2);
          return (
            `${params.seriesName}<br/>` +
            `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${params.color};"></span>` +
            `${bfb}%`
          );
        }
      },
    },
    xAxis3D: {
      min: -1,
      max: 1,
    },
    yAxis3D: {
      min: -1,
      max: 1,
    },
    zAxis3D: {
      min: -1,
      max: 1,
    },
    grid3D: {
      show: false,
      boxHeight: boxHeight, // 圆环的高度
      viewControl: {
        // 3d效果可以放大、旋转等，请自己去查看官方配置
        alpha, // 角度
        distance, // 调整视角到主体的距离，类似调整zoom
        rotateSensitivity: 0, // 设置为0无法旋转
        zoomSensitivity: 0, // 设置为0无法缩放
        panSensitivity: 0, // 设置为0无法平移
        autoRotate: false, // 自动旋转
      },
      top: "15%",
    },
    series: series,
  };
  return option;
};
// 监听鼠标事件，实现饼图选中效果（单选），近似实现高亮（放大）效果。
export const bindListen = (myChart: any, options: any) => {
  let selectedIndex = "";
  let hoveredIndex = "";
  myChart.on("click", function (params: any) {
    let isSelected = !options.series[params.seriesIndex].pieStatus.selected;
    let isHovered = options.series[params.seriesIndex].pieStatus.hovered;
    let k = options.series[params.seriesIndex].pieStatus.k;
    let startRatio = options.series[params.seriesIndex].pieData.startRatio;
    let endRatio = options.series[params.seriesIndex].pieData.endRatio;
    // 如果之前选中过其他扇形，将其取消选中（对 option 更新）
    if (selectedIndex !== "" && selectedIndex !== params.seriesIndex) {
      options.series[selectedIndex].parametricEquation = getParametricEquation(
        options.series[selectedIndex].pieData.startRatio,
        options.series[selectedIndex].pieData.endRatio,
        false,
        false,
        k,
        options.series[selectedIndex].pieData.value
      );
      options.series[selectedIndex].pieStatus.selected = false;
    }
    // 对当前点击的扇形，执行选中/取消选中操作（对 option 更新）
    options.series[params.seriesIndex].parametricEquation =
      getParametricEquation(
        startRatio,
        endRatio,
        isSelected,
        isHovered,
        k,
        options.series[params.seriesIndex].pieData.value
      );
    options.series[params.seriesIndex].pieStatus.selected = isSelected;
    // 如果本次是选中操作，记录上次选中的扇形对应的系列号 seriesIndex
    isSelected ? (selectedIndex = params.seriesIndex) : null;
    // 使用更新后的 option，渲染图表
    myChart.setOption(options);
  });
};
/**
 * 生成扇形的曲面参数方程，用于 series-surface.parametricEquation
 */
export const getParametricEquation = (
  startRatio: any,
  endRatio: any,
  isSelected: any,
  isHovered: any,
  k: any,
  h: any
) => {
  // 计算
  const midRatio = (startRatio + endRatio) / 2;
  const startRadian = startRatio * Math.PI * 2;
  const endRadian = endRatio * Math.PI * 2;
  const midRadian = midRatio * Math.PI * 2;
  // 如果只有一个扇形，则不实现选中效果。
  if (startRatio === 0 && endRatio === 1) {
    isSelected = false;
  }
  // 通过扇形内径/外径的值，换算出辅助参数 k（默认值 1/3）
  k = typeof k !== "undefined" ? k : 1 / 3;
  // 计算选中效果分别在 x 轴、y 轴方向上的位移（未选中，则位移均为 0）
  const offsetX = isSelected ? Math.cos(midRadian) * 0.1 : 0;
  const offsetY = isSelected ? Math.sin(midRadian) * 0.1 : 0;
  // 计算高亮效果的放大比例（未高亮，则比例为 1）
  const hoverRate = isHovered ? 1.05 : 1;
  // 返回曲面参数方程
  return {
    u: {
      min: -Math.PI,
      max: Math.PI * 3,
      step: Math.PI / 32,
    },
    v: {
      min: 0,
      max: Math.PI * 2,
      step: Math.PI / 20,
    },
    x: function (u: any, v: any) {
      if (u < startRadian) {
        return (
          offsetX + Math.cos(startRadian) * (1 + Math.cos(v) * k) * hoverRate
        );
      }
      if (u > endRadian) {
        return (
          offsetX + Math.cos(endRadian) * (1 + Math.cos(v) * k) * hoverRate
        );
      }
      return offsetX + Math.cos(u) * (1 + Math.cos(v) * k) * hoverRate;
    },
    y: function (u: any, v: any) {
      if (u < startRadian) {
        return (
          offsetY + Math.sin(startRadian) * (1 + Math.cos(v) * k) * hoverRate
        );
      }
      if (u > endRadian) {
        return (
          offsetY + Math.sin(endRadian) * (1 + Math.cos(v) * k) * hoverRate
        );
      }
      return offsetY + Math.sin(u) * (1 + Math.cos(v) * k) * hoverRate;
    },
    z: function (u: any, v: any) {
      if (u < -Math.PI * 0.5) {
        return Math.sin(u);
      }
      if (u > Math.PI * 2.5) {
        return Math.sin(u) * h * 0.1;
      }
      return Math.sin(v) > 0 ? 1 * h * 0.1 : -1;
    },
  };
};

type dict = {
  createBy: string;
  createTime: string;
  cssClass: string;
  default: true;
  dictCode: number;
  dictLabel: string;
  dictSort: number;
  dictType: string;
  dictValue: string;
  isDefault: string;
  listClass: string;
};
//遍历字典
export const getDictArr = (data: dict[]) => {
  console.log("遍历字典", data);

  let newArr: any[] = [];
  data.map((item: dict) => {
    item.dictValue === "0" ? "" : newArr.push(item.dictLabel);
  });
  console.log("字典数组", newArr);
  return newArr;
};

type gatewaycodeData = {
  boxId: string;
  connState: number;
  connStateTimestamp: string;
  dataType: number;
  id: string;
  name: string;
  status: number;
  timestamp: string;
  value: any;
};
//遍历运维查看数据
export const getOverViewData = (data: any, params: any[]) => {
  let newArr: any[] = [];
  data.map((item: gatewaycodeData) => {
    switch (item.name) {
      case "温度量程下限值":
        if (params.includes("lowtrange")) {
          item.value = replaceBlankSpace(item.value);
          newArr.push(item);
        }
        break;
      case "温度量程上限值":
        if (params.includes("uptrange")) {
          item.value = replaceBlankSpace(item.value);
          newArr.push(item);
        }
        break;
      case "压差量程下限值":
        if (params.includes("lowprange")) {
          item.value = replaceBlankSpace(item.value);
          newArr.push(item);
        }
        break;
      case "压差量程上限值":
        if (params.includes("upprange")) {
          item.value = replaceBlankSpace(item.value);
          newArr.push(item);
        }
        break;
      case "风速量程下限值":
        if (params.includes("lowfrange")) {
          item.value = replaceBlankSpace(item.value);
          newArr.push(item);
        }
        break;
      case "风速量程上限值":
        if (params.includes("upfrange")) {
          item.value = replaceBlankSpace(item.value);
          newArr.push(item);
        }
        break;
      case "温度报警值":
        if (params.includes("temperature")) {
          item.value = replaceBlankSpace(item.value);
          newArr.push(item);
        }
        break;
      case "压差报警值":
        if (params.includes("pa")) {
          item.value = replaceBlankSpace(item.value);
          newArr.push(item);
        }
        break;
      case "风速报警值":
        if (params.includes("flow")) {
          item.value = replaceBlankSpace(item.value);
          newArr.push(item);
        }
        break;
      case "电流报警值":
        if (params.includes("current")) {
          item.value = replaceBlankSpace(item.value);
          newArr.push(item);
        }
        break;
      case "电压报警值":
        if (params.includes("voltage")) {
          item.value = replaceBlankSpace(item.value);
          newArr.push(item);
        }
        break;
      case "电频报警值":
        if (params.includes("hz")) {
          item.value = replaceBlankSpace(item.value);
          newArr.push(item);
        }
        break;
      case "联动提示选择":
        if (params.includes("linkage")) {
          item.value = replaceBlankSpace(item.value);
          newArr.push(item);
        }
        break;
      case "环保设备维保信息链接":
        if (params.includes("link")) {
          item.value = replaceBlankSpace(item.value);
          newArr.push(item);
        }
        break;
      case "设备编号":
        if (params.includes("code")) {
          item.value = replaceBlankSpace(item.value);
          newArr.push(item);
        }
        break;
      case "设备型号":
        if (params.includes("model")) {
          item.value = replaceBlankSpace(item.value);
          newArr.push(item);
        }
        break;
      case "处理风量":
        if (params.includes("volume")) {
          item.value = replaceBlankSpace(item.value);
          newArr.push(item);
        }
        break;
      case "碳板数量":
        if (params.includes("plates")) {
          item.value = replaceBlankSpace(item.value);
          newArr.push(item);
        }
        break;
      case "活性炭重量":
        if (params.includes("repalcenum")) {
          item.value = replaceBlankSpace(item.value);
          newArr.push(item);
        }
        break;
      case "激活日期":
        if (params.includes("cTime")) {
          item.value = replaceBlankSpace(item.value);
          newArr.push(item);
        }
        break;
      case "活性炭提前提示更换时间设定":
        if (params.includes("prompt")) {
          item.value = replaceBlankSpace(item.value);
          newArr.push(item);
        }
        break;
      case "活性炭更换时间设定":
        if (params.includes("lifeValue")) {
          item.value = replaceBlankSpace(item.value);
          newArr.push(item);
        }
        break;
      case "活性炭已经使用时间总秒数":
        if (params.includes("thisTime")) {
          item.value = replaceBlankSpace(item.value);
          newArr.push(item);
        }
        break;
      // default:
      //   break;
    }
  });
  console.log("遍历运维查看数据", newArr);
  return newArr;
};

/**
 * 解决\u0000
 */
const replaceBlankSpace = (value: any) => {
  if (typeof value === "string") {
    value = value.replace(/\0/g, "");
    console.log("处理空格", value);
    return value;
  } else {
    console.log("无需处理空格", value);
    return value;
  }
};

/**
 * 获取3d丙图的最高扇区的高度
 */
const getHeight3D = (series: any, height: any) => {
  series.sort((a: any, b: any) => {
    return b.pieData.value - a.pieData.value;
  });
  return (height * 25) / series[0].pieData.value;
};

/**
 * 格式化浮点数
 */
const fomatFloat = (num: any, n: any) => {
  let f = parseFloat(num);
  if (isNaN(f)) {
    return false;
  }
  f = Math.round(num * Math.pow(10, n)) / Math.pow(10, n); // n 幂
  let s = f.toString();
  let rs = s.indexOf(".");
  // 判定如果是整数，增加小数点再补0
  if (rs < 0) {
    rs = s.length;
    s += ".";
  }
  while (s.length <= rs + n) {
    s += "0";
  }
  return s;
};

// /*
//  * 默认Url点击事件处理
//  */
// export const openUrl = (url: string, field: TableColumn) => {
//   if (field.target == "_blank") {
//     window.open(url);
//   } else {
//     window.location.href = url;
//   }
// };

/*
 * 防抖
 * @param fn 执行函数
 * @param ms 间隔毫秒数
 */
// export const debounce = (fn: any, ms: number) => {
//   let timer: null | NodeJS.Timeout = null;
//   return function (...args: any[]) {
//     if (timer !== null) {
//       clearTimeout(timer);
//       timer = null;
//     }
//     timer = setTimeout(() => {
//       fn(...args);
//     }, ms);
//   };
// };
export const debounce = (fn: any, debTime: number): any => {
  let timer: any = null;
  return (...args: any[]) => {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn(args);
      timer = null;
    }, debTime);
  };
};
// export function Debounce(fun: any, wait: number = 1000) {
//   let timer: any;
//   return function () {
//     if (timer) {
//       clearTimeout(timer);
//     }
//     let isNow = !timer;
//     timer = setTimeout(() => {
//       timer = null;
//     }, wait);
//     if (isNow) fun();
//   };
// }
export function throttle(fun: any, wait: number = 1000) {
  let timers: any;
  return function () {
    if (!timers) {
      timers = setTimeout(() => {
        fun;
        timers = null;
      }, wait);
    }
  };
}

export const filterParams = (data: any) => {
  let { createTime, pageSize, pageNum, ...newObj } = data;
  // if (Reflect.deleteProperty(data, "createTime")) {
  //   console.log("删除是否成功", data);
  //   return data;
  // }
  console.log("filterParams??", newObj);

  return newObj;
};

//处理导出接口的this.table.filter
export const filterParamsNormal = async (data: any) => {
  let obj: any = {};
  for (const key in data) {
    if (key === "search" && data.search.length > 0) {
      let otherObj = await getFilterParams(data.search);
      Object.assign(obj, otherObj);
    } else {
      obj[key] = data[key];
    }
  }
  console.log("处理导出接口", obj);
  return obj;
};
const getFilterParams = (data: any) => {
  let newObj: any = {};
  for (let index = 0; index < data.length; index++) {
    newObj[data[index].field] = data[index].val;
  }
  return newObj;
};

/*
 * 远程下拉框数据获取
 */
export function getSelectData(remoteUrl: string, q: string, params: {}) {
  return new Promise((resolve, reject) => {
    _get(remoteUrl, params, "json", "")
      .then((res) => {
        console.log(res);
        resolve(res);
      })
      .catch((err) => {
        console.log(err);
        reject(err);
      });
  });
}

/*
 * 将企业数据转化为Map格式
 */

export const mapCompanies = (res: any) => {
  return new Map(res.rows.map((item: any) => [item.id, item.name]));
};

/*
 * 格式化时间戳
 */
export const timeFormat = (
  dateTime: string | number | null = null,
  fmt = "yyyy-mm-dd hh:MM:ss"
) => {
  if (dateTime == "none") return "none";
  if (!dateTime) dateTime = Number(new Date());
  if (dateTime.toString().length === 10) {
    dateTime = +dateTime * 1000;
  }
  const date = new Date(dateTime);
  let ret;
  const opt: any = {
    "y+": date.getFullYear().toString(), // 年
    "m+": (date.getMonth() + 1).toString(), // 月
    "d+": date.getDate().toString(), // 日
    "h+": date.getHours().toString(), // 时
    "M+": date.getMinutes().toString(), // 分
    "s+": date.getSeconds().toString(), // 秒
  };
  for (const k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt);
    if (ret) {
      fmt = fmt.replace(
        ret[1],
        ret[1].length == 1 ? opt[k] : padStart(opt[k], ret[1].length, "0")
      );
    }
  }
  return fmt;
};

/**
 * 获取昨天日期
 *
 * @returns
 */
export const getYesterday = () => {
  let d = new Date();
  d.setDate(d.getDate() - 1);
  return d;
};
/**
 * 计算活性炭减排量
 */
export const VOCS = (data: any[]) => {
  return new Promise((resolve, reject) => {
    let arr: any = [];
    for (let i = 0, len = data.length; i < len; i++) {
      arr.push(Number((data[i] * 0.2).toFixed(1)));
    }
    console.log("减排", arr);
    resolve(arr);
  });
};
export const origin = (data: any[]) => {
  return new Promise((resolve, reject) => {
    let arr: any = [];
    for (let i = 0, len = data.length; i < len; i++) {
      arr.push(Number((data[i] / 0.2).toFixed(1)));
    }
    console.log("原始", arr);
    resolve(arr);
  });
};
/*
 * 字符串补位
 */
export const padStart = (str: string, maxLength: number, fillString = " ") => {
  if (str.length >= maxLength) return str;

  const fillLength = maxLength - str.length;
  let times = Math.ceil(fillLength / fillString.length);
  while ((times >>= 1)) {
    fillString += fillString;
    if (times === 1) {
      fillString += fillString;
    }
  }
  return fillString.slice(0, fillLength) + str;
};

/*
 * 判断当前是否在后台/admin中
 */
export const isAdminApp = () => {
  // console.log(
  //   "router.currentRoute.value.fullPath",
  //   router.currentRoute,
  //   router.currentRoute.value.fullPath
  // );
  if (
    /^\/admin/.test(router.currentRoute.value.fullPath) ||
    window.location.hash.indexOf("#/admin") === 0
  ) {
    return true;
  }
  return false;
};

/*
 * 根据pk字段的值从数组中获取key
 * @param arr
 * @param pk
 * @param value
 */
export const getArrayKey = (arr: any, pk: string, value: string): any => {
  for (const key in arr) {
    if (arr[key][pk] == value) {
      return key;
    }
  }
  return false;
};
interface ElTreeData {
  label: string;
  children?: ElTreeData[];
}
/**
 * 将数据构建为ElTree的data {label:'', children: []}
 * @param data
 */
export const buildJsonToElTreeData = (data: any): ElTreeData[] => {
  if (typeof data == "object") {
    const childrens = [];
    for (const key in data) {
      childrens.push({
        label: key + ": " + data[key],
        children: buildJsonToElTreeData(data[key]),
      });
    }
    return childrens;
  } else {
    return [];
  }
};

/**
 * 工艺管理 bom树去重
 */
export const processBomTree = (data: any) => {
  let newArr = _.cloneDeep(data);
  for (let i = 0, len = newArr.length; i < len; i++) {
    newArr[i].children = uniqueBom(newArr[i]);
  }
  console.log("newArr", newArr);
  return newArr;
};
const uniqueBom = (Obj: anyObj) => {
  let newArr = [];
  let map = new Map();
  if (Obj.children.length == 0 || Obj.type === "采购件") return;
  for (let i = 0, len = Obj.children.length; i < len; i++) {
    if (Obj.children[i].children.length > 0) {
      Obj.children = uniqueBom(Obj.children[i].children);
    }
    if (!map.has(Obj.children[i].code) && Obj.children[i].type !== "采购件") {
      map.set(Obj.children[i].code, true);
      newArr.push(Obj.children[i]);
    }
  }
  return newArr;
};

/**补齐设备数量展示 */
export const completeDevices = (arr: any[]) => {
  let len = arr.length;
  switch (len) {
    case 1:
      switch (arr[0].estate) {
        case 0:
          return [
            { value: arr[0].value, estate: arr[0].estate },
            { value: 0, estate: 1 },
            { value: 0, estate: 2 },
          ];
        case 1:
          return [
            { value: arr[0].value, estate: arr[0].estate },
            { value: 0, estate: 0 },
            { value: 0, estate: 2 },
          ];
        default:
          return [
            { value: arr[0].value, estate: arr[0].estate },
            { value: 0, estate: 0 },
            { value: 0, estate: 1 },
          ];
      }
    case 2:
      let temp: any[] = [];
      for (let i = 0; i < len; i++) {
        temp.push(arr[i].estate);
      }
      if (!temp.includes(0)) {
        arr.push({ value: 0, estate: 0 });
        return arr;
      } else if (!temp.includes(1)) {
        arr.push({ value: 0, estate: 1 });
        return arr;
      } else {
        arr.push({ value: 0, estate: 2 });
        return arr;
      }
    default:
      return arr;
  }
};

/*
 * 页面操作栏显隐
 */
export const operatorShowOff = (arr: string[]): any => {
  console.log("页面操作栏显隐", arr);
  if (arr.length === 0) return true;
  const navTabs = useNavTabs();
  // console.log(
  //   "navTabs.state.authNode",
  //   navTabs.state.authNode.size,
  //   navTabs.state.authNode.get("/admin/")
  // );
  if (
    navTabs.state.authNode.size !== 0 &&
    navTabs.state.authNode.get("/admin/")![0] === "*:*:*"
  ) {
    return true;
  }
  let Nodes = JSON.parse(JSON.stringify(navTabs.state.authNodes));
  console.log("权限节点：", Nodes);

  for (let i = 0; i < arr.length; i++) {
    if (Nodes.includes(arr[i])) {
      return true;
    } else {
      continue;
    }
  }
  return false;
};

/*
 * 页面按钮鉴权
 * @param name
 */
export const auth = (name: string) => {
  const navTabs = useNavTabs();

  if (navTabs.state.authNode.get("/admin/")![0] === "*:*:*") {
    return true;
  }
  let Nodes = JSON.parse(JSON.stringify(navTabs.state.authNodes));
  if (Nodes.includes(router.currentRoute.value.path + "/" + name)) {
    return true;
  }
  return false;
};

/*
 * 重组分析分项数据
 */
export class AnalysisReset {
  // 重组分析分项数据
  resetFields = (data: any[]) => {
    return new Promise((resolve: any, reject) => {
      let len = data.length;
      let newObj: any = {};
      let set: any = new Set();
      for (let i = 0; i < len; i++) {
        if (data[i].electricName) {
          if (set.has(data[i].electricName)) {
            newObj[data[i].electricName].push(data[i]);
          } else {
            set.add(data[i].electricName);
            newObj[data[i].electricName] = [data[i]];
          }
        }
      }
      resolve(newObj);
    });
  };
  // 重组不同用能标签
  resetTag = (data: any, store: any, filterLen: any) => {
    return new Promise((resolve: any, reject) => {
      let rows: any = [];
      for (const key in data) {
        let bigobj: any = {
          summary: "",
          siteName: "",
          cabinetName: "",
          gcode: "",
          count: "",
        };
        for (let i = 0; i < data[key].length; i++) {
          let time: any = data[key][i].createTime.split(" ");
          let params: any = "";
          if (filterLen === 3) {
            params = time[1].split(":")[0];
          }
          if (filterLen === 2) {
            params = time[0].split("-")[2];
          }
          if (filterLen === 1) {
            params = time[0].split("-")[1];
          }
          bigobj[Number(params) + store.unit] = data[key][i].num;
          bigobj.gcode = data[key][i].gcode;
          bigobj.summary = data[key][i].electricLabel;
        }
        rows.push(bigobj);
      }
      resolve(rows);
    });
  };
  // 重组电表数据
  resetGateway = (data: any[]) => {
    return new Promise((resolve: any, reject) => {
      let len = data.length;
      let setData: any = new Map(); //类似config
      let arr: any = [];
      for (let i = 0; i < len; i++) {
        if (data[i].electricName) {
          if (!setData.has(data[i].gcode)) {
            setData.set(data[i].gcode, data[i].electricName);
            arr.push(data[i].gcode);
          }
        }
      }
      resolve(arr);
    });
  };
  getCabinetName = (arr: any, store: any) => {
    return arr.map((item: any) => {
      return store.getCabinet({ gatewayCode: item }).then((res: any) => {
        if (!store.cabinetNameArrForTable.has(item)) {
          store.cabinetNameArrForTable.set(item, res[0].siteName);
        }
      });
    });
  };
}

//baTableApi 生成对应api下增删查改路径
export class baTableApi {
  // private controllerUrl; //私类
  public controllerUrl; //私类
  public actionUrl; //公开类

  constructor(controllerUrl: string) {
    this.controllerUrl = controllerUrl;
    //功能模块的增删改查接口
    this.actionUrl = new Map([
      ["index", controllerUrl],
      ["add", controllerUrl],
      ["edit", controllerUrl],
      ["del", controllerUrl],
      ["audit", controllerUrl],
      ["list", controllerUrl + "/list"],
      ["itemAdd", controllerUrl], //单个菜单增加子项
      ["origin", controllerUrl],
      ["history", controllerUrl + "/list"], //实时监控历史数据模块
      ["changeStatus", controllerUrl + "/changeStatus"], //用户管理切换状态
      ["export", controllerUrl + "/export"], //列表导出管理
    ]);
  }
  //查询功能 主要是获取table列表数据
  index(filter: any = {}) {
    return new Promise((resolve, reject) => {
      let url = this.actionUrl.get("index");
      resolve(url);
      _get(url!, filter, "json", "")
        .then((res) => {
          console.log(res);
          resolve(res as any);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }
  //编辑功能 打开编辑啊表单
  edit(id: any) {
    //new Map().get()方法 es6
    return new Promise((resolve, reject) => {
      let url = this.actionUrl.get("edit") + "/" + id;
      _get(url!, "", "json", "")
        .then((res) => {
          resolve(res as any);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }
  //删除功能
  del(ids: string[]) {
    return new Promise((resolve, reject) => {
      let url = this.actionUrl.get("del") + "/" + ids;
      _delete(url!, ids, "json", "")
        .then((res) => {
          resolve(res as any);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }
  //上传表单
  postData(action: string, data: any) {
    console.log("action?", data);
    if (!this.actionUrl.has(action)) {
      throw new Error("action 不存在！");
    }
    //主要因为编辑后提交表单后端api方法为put
    switch (action) {
      case "edit":
        return new Promise((resolve, reject) => {
          let url = this.actionUrl.get(action);
          _put(url!, data, "json", "")
            .then((res) => {
              console.log(res);
              resolve(res as any);
            })
            .catch((err) => {
              reject(err);
            });
        });
      case "origin":
        //设备接入初始化
        return new Promise((resolve, reject) => {
          _post("/system/estate", data, "json", "")
            .then((res) => {
              console.log("初始化之后修改", res);
              const access = useAccess();
              const carbon = useCarbon();
              _put("/system/equipment", access.item, "json", "")
                .then((res) => {
                  console.log(res);
                  resolve(res as any);
                })
                .catch((err) => {
                  reject(err);
                });
              resolve(res as any);
            })
            .catch((err) => {
              reject(err);
            });
        });
      default:
        //新增方法用post
        return new Promise((resolve, reject) => {
          let url = this.actionUrl.get(action);
          _post(url!, data, "json", "")
            .then((res) => {
              console.log(res);
              resolve(res as any);
            })
            .catch((err) => {
              reject(err);
            });
        });
    }
  }
  //给实时监控历史模块数据
  history(type: string, filter: any = {}) {
    const monitor = useBackendMonitor();
    monitor.historyFilter = filter;
    for (const key in filter) {
      if (key === "createTime") {
        delete filter.createTime;
      }
    }
    console.log("给实时监控历史模块数据", filter, monitor.historyFilter);
    filter.params = {};
    let url = this.actionUrl.get("history");
    return new Promise((resolve, reject) => {
      _get(
        url! + "?" + qs.stringify(filter, { arrayFormat: "indices" }),
        {},
        "json",
        ""
      )
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          console.log(err);
          reject(err);
        });
    });
  }
  search(type: string, filter: any = {}) {
    if (this.controllerUrl == "/system/eqattribute") {
      return new Promise((resolve, reject) => {
        _get("/system/eqattribute/nowlistbylist", filter, "json", "")
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    } else if (this.controllerUrl == "/system/estate") {
      return new Promise((resolve, reject) => {
        _get("/system/estate/listByregions", filter, "json", "")
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    } else if (this.controllerUrl == "/system/equipment") {
      //设备接入配合过滤树
      return new Promise((resolve, reject) => {
        _get(
          "/system/equipment/list?" +
            qs.stringify(filter, { arrayFormat: "indices" }),
          {},
          "json",
          ""
        )
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    } else if (this.controllerUrl == "/system/warning") {
      let newFilter = _.cloneDeep(filter);
      delete newFilter["reportTime"];
      let url = this.actionUrl.get("list");
      return new Promise((resolve, reject) => {
        _get(
          url + "?" + qs.stringify(newFilter, { arrayFormat: "indices" }),
          {},
          "json",
          ""
        )
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    } else if (this.controllerUrl == "/system/Bequipment") {
      //设备接入
      return new Promise((resolve, reject) => {
        _get("/system/equipment/list", filter, "json", "")
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    } else if (this.controllerUrl === "/system/dict/data/type") {
      //字典详细
      return new Promise((resolve, reject) => {
        _get("/system/dict/data/type/" + filter?.dictType, {}, "json", "")
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    } else {
      let url = this.actionUrl.get("list");
      console.log("daozheli!!!!", url, filter);
      return new Promise((resolve, reject) => {
        _get(
          url + "?" + qs.stringify(filter, { arrayFormat: "indices" }),
          {},
          "json",
          ""
        )
          .then((res: any) => {
            resolve(res);
            if (this.controllerUrl == "/system/alarm" && filter.eid) {
              const monitor = useBackendMonitor();
              monitor.eventDone = false; //事件图表重置
              monitor.$patch((state) => {
                state.on = [];
                state.off = [];
                state.warn = [];
                state.change = [];
              }); //事件图表数据重置
              monitor.handleDevicesEvent(res.rows);
            }
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    }
  }
  //获取list方法的接口
  list(type: string, filter: any = {}) {
    const file = useLedgerFile(); //台账文件管理 企业进入方法
    if (this.controllerUrl == "/system/eqattribute") {
      return new Promise((resolve, reject) => {
        _get("/system/eqattribute/nowlistbylist", filter, "json", "")
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    } else if (this.controllerUrl == "/system/estate") {
      return new Promise((resolve, reject) => {
        _get("/system/estate/listByregions", filter, "json", "")
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    } else if (this.controllerUrl == "/system/site") {
      return new Promise((resolve, reject) => {
        _get("/system/site/oldlist", filter, "json", "")
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    } else if (this.controllerUrl == "/system/equipment") {
      //设备接入配合过滤树
      return new Promise((resolve, reject) => {
        _get("/system/equipment/list", filter, "json", "")
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    } else if (this.controllerUrl == "/system/Bequipment") {
      //设备接入
      return new Promise((resolve, reject) => {
        _get("/system/equipment/list", filter, "json", "")
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    } else if (this.controllerUrl === "/system/dict/data/type") {
      //字典详细
      return new Promise((resolve, reject) => {
        const dict = useDictionary();
        _get("/system/dict/data/type/" + filter?.dictType, {}, "json", "")
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    } else if (this.controllerUrl === "/system/file" && file.orderId !== 0) {
      return new Promise((resolve, reject) => {
        filter.orderId = file.orderId;
        _get("/system/file/list", filter, "json", "")
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    } else if (this.controllerUrl === "/system/detailed/RingAnalysis") {
      return new Promise((resolve, reject) => {
        let url = this.actionUrl.get("list");
        _get(
          url! + "?" + qs.stringify(filter, { arrayFormat: "indices" }),
          {},
          "json",
          ""
        )
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    } else if (
      (this.controllerUrl === "/system/standard" &&
        router.currentRoute.value.fullPath === "/admin/task/detail") ||
      this.controllerUrl === "/system/electricEnvpub"
    ) {
      let url = this.actionUrl.get("list");
      return new Promise((resolve, reject) => {
        _get(
          url! + "?" + qs.stringify(filter, { arrayFormat: "indices" }),
          {},
          "json",
          ""
        )
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    } else if (this.controllerUrl === "/system/electricEnvpub/listBycode") {
      return new Promise((resolve, reject) => {
        console.log("接收站点树传递过来的数据listBycode", filter);
        _get(
          `/system/electricEnvpub/listBycode/${filter.siteIds}`,
          { type: filter.type },
          "json",
          ""
        )
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    } else if (this.controllerUrl === "/system/warning") {
      //批量查询站点id
      return new Promise((resolve, reject) => {
        let url = this.actionUrl.get("list");
        _get(
          url! + "?" + qs.stringify(filter, { arrayFormat: "indices" }),
          {},
          "json",
          ""
        )
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    } else if (this.controllerUrl === "/system/detailed/SubitemByDay") {
      //批量查询站点id
      return new Promise((resolve, reject) => {
        let filterLen = filter.date.split("-").length;
        let url =
          filterLen === 3
            ? this.actionUrl.get("list")
            : filterLen === 2
            ? "/system/detailed/SubitemByMonth/list"
            : "/system/detailed/SubitemByYear/list";
        _get(
          url! + "?" + qs.stringify(filter, { arrayFormat: "indices" }),
          {},
          "json",
          ""
        )
          .then((result: any) => {
            console.log("批量查询站点id", result);
            const analysis = useElectricSubitemByDay();
            const reset = new AnalysisReset();
            // 重组电表数据 电表内网关对应的机柜名称
            reset.resetGateway(result.rows).then(async (res: any) => {
              const promises = reset.getCabinetName(res, analysis);
              Promise.all(promises).then(() => {
                // 重组分析分项数据
                reset.resetFields(result.rows).then((res: any) => {
                  reset
                    .resetTag(res, analysis, filterLen)
                    .then((res: any) => {
                      let len = res.length;
                      for (let i = 0; i < len; i++) {
                        res[i].cabinetName =
                          analysis.cabinetNameArrForTable.get(res[i].gcode);
                      }
                      resolve({ rows: res, total: res.length });
                    })
                    .catch((err: any) => {});
                });
              });
            });
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    } else if (this.controllerUrl === "/system/cabinet") {
      return new Promise((resolve, reject) => {
        let url = this.actionUrl.get("list");
        _get(
          url! + "?" + qs.stringify(filter, { arrayFormat: "indices" }),
          {},
          "json",
          ""
        )
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    } else {
      let url = this.actionUrl.get("list");
      return new Promise((resolve, reject) => {
        _get(url!, filter, "json", "")
          .then((res: any) => {
            console.log("获取list方法的接口", res, this.controllerUrl);
            resolve(res);
            if (
              this.controllerUrl == "/system/alarm" &&
              filter.gatewaycode &&
              router.currentRoute.value.fullPath !== "/admin/system/alarm"
            ) {
              const monitor = useBackendMonitor();
              const warnLog = useWarnLog();
              const region = useRegion();
              monitor.eventDone = false; //事件图表重置
              monitor.$patch((state) => {
                state.on = [];
                state.off = [];
                state.warn = [];
                state.change = [];
              }); //事件图表数据重置
              monitor.handleDevicesEvent(res.rows);
            }
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    }
  }
  //switch切换状态
  switch(action: string, data: any) {
    if (!this.actionUrl.has(action)) {
      throw new Error("action 不存在！");
    }
    let url = this.actionUrl.get(action);
    return new Promise((resolve, reject) => {
      _put(url!, data, "json", "")
        .then((res) => {
          console.log(res);
          resolve(res as any);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }
  //审核接口
  auditApi() {}

  //!导出文件接口 默认导出第一页十个数据
  export(filter: any = {}) {
    let url = this.actionUrl.get("export");
    return new Promise((resolve, reject) => {
      // let url = this.actionUrl.get("export");
      _download(url!, filter, `导出列表_${new Date().getTime()}.xlsx`)
        .then((res) => {
          resolve(res as any);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }
}

/**
 * 参数处理通用下载
 */
export const tansParams = (params: any) => {
  let result = "";
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    var part = encodeURIComponent(propName) + "=";
    if (value !== null && value !== "" && typeof value !== "undefined") {
      if (typeof value === "object") {
        for (const key of Object.keys(value)) {
          if (
            value[key] !== null &&
            value[key] !== "" &&
            typeof value[key] !== "undefined"
          ) {
            let params = propName + "[" + key + "]";
            var subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result;
};

// 验证是否为blob格式
export async function blobValidate(data: any) {
  try {
    const text = await data.text();
    JSON.parse(text);
    return false;
  } catch (error) {
    return true;
  }
}
